package com.example.activity;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.R;
import com.example.entity.Bookmark;
import com.example.entity.Capture;
import com.example.module.satellite.SatelliteMenu;
import com.example.module.satellite.SatelliteMenu.SateliteClickedListener;
import com.example.module.satellite.SatelliteMenuItem;
import com.example.module.widget.CustomBrowser;
import com.example.persistence.BaseActivity;
import com.example.util.FileUtil;
import com.example.util.ImageUtil;
import com.example.util.SharedPreferenceUtil;
import com.example.util.StringUtil;

public class MainActivity extends BaseActivity {
	protected static final String TAG = "MainActivity";

	private boolean isBackPressed;
	
//	private SatelliteMenu menu;
	private CustomBrowser webBrowser;
	private WebView webView;
	private ImageView preloadImage;
	
	private AtomicBoolean animationActive = new AtomicBoolean(false);
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
 		// initialize and setup Bottom Menu Bar
		initializeMenu();
		
		// initialize and setup Address Bar / WebView
		preloadImage = (ImageView) findViewById(R.id.preloadImage);
        webBrowser = (CustomBrowser) findViewById(R.id.webBrowser);
        webBrowser.setBrowserActionListener(new CustomBrowser.BrowserActionListener() {
			@Override
			public void onBookmarkClick() {
				doBookmark(getBookmarkFileName());
			}

			@Override
			public void onOverlayClick() {
//				menu.close();
			}

			@Override
			public void onBookmarkCheck(String url) {
				checkBookmark(url);
			}
		});
        
        webView = webBrowser.getWebView();
        
        String startUrl = StringUtil.nvl(SharedPreferenceUtil.getString(this, "currentUrl"), DEFAULT_URL);
        webBrowser.loadUrl(startUrl);
    }
	
	private void initializeMenu() {
//		menu = (SatelliteMenu) findViewById(R.id.menu);

		/*
		float distance = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, getResources().getDisplayMetrics());
		menu.setSatelliteDistance((int) distance);
		menu.setExpandDuration(500);
		menu.setCloseItemsOnClick(true);
		menu.setTotalSpacingDegree(90);

		List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>();
		items.add(new SatelliteMenuItem(ITEM_CAPTURE, R.drawable.menu_capture));
		items.add(new SatelliteMenuItem(ITEM_CAPTURE_WHOLE, R.drawable.menu_capture_all));
		items.add(new SatelliteMenuItem(ITEM_CAPTURE_SHOW, R.drawable.menu_capture_view));
		items.add(new SatelliteMenuItem(ITEM_BOOKMARK, R.drawable.menu_bookmark));
		items.add(new SatelliteMenuItem(ITEM_BOOKMARK_SHOW, R.drawable.menu_bookmark_view));
		items.add(new SatelliteMenuItem(ITEM_CLEAR_ALL, R.drawable.menu_delete));
		menu.addItems(items);
		
		menu.setOnChangedStatusListner(new SatelliteMenu.OnChangedStatusListner() {
			@Override
			public void onChangedStatus(boolean rotated) {
				webBrowser.displayOverlay(!rotated);
			}
		});
      
		menu.setOnItemClickedListener(new SateliteClickedListener() {
			public void eventOccured(int id, boolean rotated) {
				
				Log.i("sat", "Menu Item Clicked on " + id + " rotated=" + rotated);
				
				if (rotated) {
					return;
				}
				
				String key, fileName, thumbnailFileName;
				
				switch (id) {
				case ITEM_CAPTURE:
					doCapture(getCaptureFileName(), false);
					break;
					
				case ITEM_CAPTURE_WHOLE:
					doCapture(getCaptureFileName(), true);
					break;
					
				case ITEM_CAPTURE_SHOW:
					Intent intent = new Intent(MainActivity.this, CaptureGridActivity.class);
					intent.putExtra(SWITCH_ANIMATION, false);
					startActivity(intent);
					break;
					
				case ITEM_BOOKMARK:
					doBookmark(getBookmarkFileName());
					break;
					
				case ITEM_BOOKMARK_SHOW:
					startActivityForResult(new Intent(MainActivity.this, BookmarkListActivity.class), BOOKMARK_CODE);
					break;

				case ITEM_CLEAR_ALL:
					alert("모든 데이터를 삭제 하시겠습니까?",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							clearAllData(application.getBookmarkList());		
						}
					},
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
					break;
					
				default:
					break;
				}
				
			}
		});
		*/
	}

	@Override
	protected void onResume() {
		isBackPressed = false;
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	@Override
	protected void onStop() {
		SharedPreferenceUtil.putString(this, "currentUrl", webBrowser.getCurrentUrl());
		super.onStop();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e("ShoppingBookmarkActivity onActivityResult", "requestCode=" + requestCode + " resultCode=" + resultCode + " data=" + data);
		
		switch (requestCode) {
		case BOOKMARK_CODE :
//			ActivitySwitcher.animationIn(container, getWindowManager());
			break;
		default:
			break;
		}
		
		switch (resultCode) {
		case LOAD_URL_CODE :
			String url = data.getStringExtra("url");
//			Log.d("ShoppingBookmarkActivity onActivityResult", "url=" + url);
			if (url != null && !"".equals(url))
				webView.loadUrl(url);
			break;

		default:
			break;
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	@Override
	public void onBackPressed() {
//		Log.d("onBackPressed", "menu.isRotated()=" + menu.isRotated() + " webView.canGoBack()=" + webView.canGoBack() + " isBackPressed=" + isBackPressed);
		
//		if (menu.isRotated())
//			menu.close();
		
		if (webView.canGoBack())
			webView.goBack();
		else if (!isBackPressed) {
			isBackPressed = true;
			Toast.makeText(getApplicationContext(), getString(R.string.message_confirm_finish), Toast.LENGTH_SHORT).show();
		}
		else
			finish();
	}
	
	public void checkBookmark(String url) {
		for (int i = 0; application.getBookmarkList() != null && i < application.getBookmarkList().size(); i++) {
			Bookmark bookmark = application.getBookmarkList().get(i);
			if (bookmark.getUrl().equals(url)) {
				webBrowser.activateBookmark(true);
				return;
			}
		}
		
		webBrowser.activateBookmark(false);
	}
	
	public void doBookmark(final String file) {
		if (animationActive.compareAndSet(false, true)) {
			
			AsyncTask<Void, Integer, Boolean> bookmarkTask = new AsyncTask<Void, Integer, Boolean>(){
				Bitmap bitmap, thumbnail;
				
				@Override
				protected void onPreExecute() {
					bitmap = ImageUtil.getCapturedScreen(webView);
					thumbnail = ImageUtil.resizeBitmap(bitmap, 200, 200);
					webBrowser.animateBookmarkShot(bitmap);
					super.onPreExecute();
				}
				
				@Override
				protected Boolean doInBackground(Void... params) {
					if (thumbnail == null || thumbnail.isRecycled())
						return false;

					boolean result = FileUtil.saveBitmap(thumbnail, file);
					
					while (!webBrowser.isAnimationFinished) {
						try { Thread.sleep(700); }
						catch (InterruptedException e) { e.printStackTrace(); }
					}
					webBrowser.isAnimationFinished = false;
					
					return result;
				}
				
				@Override
				protected void onPostExecute(Boolean result) {
					Log.e(TAG, "doBookmark result=" + result);
					
				    if (result) {
				    	String url = webView.getUrl();
						String title = webView.getTitle();
						
				    	Bookmark bookmark = new Bookmark();
				    	bookmark.setPath(FileUtil.ANDROID_FILE_PREFIX + file);
				    	bookmark.setUrl(url);
				    	bookmark.setTitle(title);
				    	application.getBookmarkList().add(bookmark);
//				    	menu.animateSuccess();
				    	checkBookmark(url);
				    }
				    else
//				    	menu.animateFail();
				    
				    webView.destroyDrawingCache();
				    animationActive.set(false);
					super.onPostExecute(result);
				}
			};
			bookmarkTask.execute();
		}
	}
	
	public void doCapture(final String file, final boolean isWhole) {
		if (animationActive.compareAndSet(false, true)) {
			
			AsyncTask<Void, Integer, Boolean> catureTask = new AsyncTask<Void, Integer, Boolean>(){
				Bitmap bitmap, thumbnail;
				String thumbnailFile;
				byte[] originImage;
				
				@Override
				protected void onPreExecute() {
					bitmap = isWhole ? ImageUtil.getCapturedWholeScreen(webView) : ImageUtil.getCapturedScreen(webView);
					thumbnail = ImageUtil.resizeBitmap(bitmap, preloadImage);
					thumbnailFile = FileUtil.getThumbnailFileName(file);
					
					webBrowser.animateCaptureShot();
					
					ByteArrayOutputStream stream = new ByteArrayOutputStream();
					bitmap.compress(CompressFormat.PNG, 100, stream);
					originImage = stream.toByteArray();
					
					super.onPreExecute();
				};

				@Override
				protected Boolean doInBackground(Void... params) {
					if (thumbnail == null || thumbnail.isRecycled())
						return false;

					boolean result = FileUtil.saveBitmap(thumbnail, thumbnailFile);					
					
					while (!webBrowser.isAnimationFinished) {
						Log.e(TAG, "isAnimationFinished=" + webBrowser.isAnimationFinished);
						try { Thread.sleep(700); }
						catch (InterruptedException e) { e.printStackTrace(); }
					}
					webBrowser.isAnimationFinished = false;
					
					return result;
				}
				
				@Override
				protected void onPostExecute(final Boolean result) {
					Log.e(TAG, "doCapture result=" + result);
					
				    if (result) {
//				    	menu.animateSuccess();
				    	Capture capture = new Capture(FileUtil.ANDROID_FILE_PREFIX + file, FileUtil.getTimestampFromFileName(file), FileUtil.ANDROID_FILE_PREFIX + thumbnailFile);
				    	application.getCaptureList().add(0, capture);
				    	
				    	notifyCaptureFile();
				    	
				    	new Thread(new Runnable() {
							
							@Override
							public void run() {
								
								boolean originResult = FileUtil.write(file, originImage);
//						    	boolean originResult = FileUtil.saveBitmap(bitmap, file);
								
						    	Log.e(TAG, "originResult=" + originResult);
							}
						}).start();
				    }
				    else
//						menu.animateFail();

				    webView.destroyDrawingCache();
				    animationActive.set(false);	
					
					super.onPostExecute(result);
				}
			};
			catureTask.execute(); 
		}
	}
}